﻿using Basic.FormCollect;
using Basic.FormRemoteModel.PageCalculate.Model;
using Basic.UserFormService.Interface;
using Basic.UserFormService.Model;
using Basic.UserFormService.Page.Interface;
using WeDonekRpc.Helper;
using WeDonekRpc.SqlSugar;
using WeDonekRpc.SqlSugar.VirtualQuery;

namespace Basic.UserFormService.Page
{
    internal class StatisticsCalculate : IStatisticsCalculate
    {
        private readonly IPageStatisticsService _Statistics;
        private readonly IAgentFormCollect _AgentForm;

        public StatisticsCalculate ( IPageStatisticsService statistics, IAgentFormCollect agentForm )
        {
            this._Statistics = statistics;
            this._AgentForm = agentForm;
        }

        public decimal? Calculate ( CalculateArg arg )
        {
            StatisticsBody body = this._Statistics.Get(arg.Id, arg.CompanyId, arg.Extend);
            if ( body.Query == null )
            {
                return null;
            }
            QueryStruct query;
            if ( !arg.Search.IsNull() )
            {
                IWhereCol[] where = arg.Search.GetWhere(body.Cols);
                query = body.Query.Clone();
                query.Where = query.Where.Merge(where);
            }
            else
            {
                query = body.Query;
            }
            dynamic res = this._AgentForm.Get(query);
            if ( res != null )
            {
                IDictionary<string, object> dic = (IDictionary<string, object>)res;
                if ( dic.TryGetValue(body.ColName, out object val) && val != null )
                {
                    return Convert.ToDecimal(val);
                }
            }
            return null;
        }
    }
}
